import React, {
  useState,
  useRef,
  useEffect,
  memo,
  useLayoutEffect,
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Alert, Typography, Button, Modal, Form, Input } from 'antd';
import { connect } from 'dva';
import { useIntl, FormattedMessage } from 'umi';
// import { Label } from '_bizcharts@3.5.9@bizcharts';
import styles from './index.less';

const itemStyle = {
  margin: ' 0 0.5rem 0.6rem',
};

const formLayout = {
  labelCol: { xs: 4, sn: 4 },
  wrapperCol: { xs: 24, sm: 20 },
};
let BMap = window.BMap;
//创建图标
let blueIcon = new BMap.Icon(
  'http://api.map.baidu.com/lbsapi/creatmap/images/us_mk_icon.png',
  new BMap.Size(23, 25),
  {
    offset: new BMap.Size(10, 2), // 指定定位位置
    imageOffset: new BMap.Size(0 - 1 * 23, 0 - 1 * 22.5), // 设置图片偏移使用左侧的图片
    //  imageOffset: new BMap.Size(-20, 0 - 1 * 25) // 设置图片偏移使用右侧的图片0-x*25代表使用第x+1张图片
  },
);
let map = {};
const CodePreview = ({ children }) => (
  <pre className={styles.pre}>
    <code>
      <Typography.Text copyable>{children}</Typography.Text>
    </code>
  </pre>
);

const CollectionCreateForm = memo(
  ({ props, visible, onCreate, onCancel, type, record }) => {
    //子组件
    const [form] = Form.useForm();
    form.setFieldsValue(record);
    const onOK = () => {
      form
        .validateFields()
        .then((values) => {
          // console.log(values);
          props.dispatch({
            type: 'construction/add',
            payload: values,
          });
          visible = false;
          var pt = new BMap.Point(values.latitude, values.longitude);
          var marker = new BMap.Marker(pt, {
            icon: blueIcon,
          });
          map.addOverlay(marker);
          var opts = {
            width: 210,
            height: 125,
            title: '<p>' + values.constructionSiteName + '</p>',
            enableMessage: true, //设置允许信息窗发送短息
            message: '',
          };
          // var infoWindow = new BMap.InfoWindow("<br>创建时间："+item.createTime + "<br>经度：" + item.latitude + "<br>纬度" + item.longitude, opts )
          // marker.addEventListener('click', function () {
          //   // console.log('123');
          //   this.map.openInfoWindow(infoWindow, pt)
          // })
          // rightClickMarker(marker, pt, item);
        })
        .catch((info) => {});
    };

    return (
      <Modal
        title="添加工地"
        onCancel={onCancel}
        // onOk = {onCreate}
        visible={visible}
        onOk={onOK}
      >
        <Form
          {...formLayout}
          // initialValues={records} 默认值，动态值用setFieldsValue
          form={form}
        >
          <Form.Item
            name="constructionSiteName"
            label="工地名称"
            rules={[{ required: true, message: '请输入工地名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="latitude"
            label="纬度"
            rules={[{ required: true, message: '请输入纬度' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="longitude"
            label="经度"
            rules={[{ required: true, message: '请输入经度' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    );
  },
);

const HomePage = (props) => {
  const [visible, setVisible] = useState(false);
  const intl = useIntl();
  const mapRef = useRef();

  const rightClickMarker = (marker, pt, site) => {
    var watchDelMarker = (e, ee, marker) => {
      // console.log(e,ee);
      console.log(site);
      const constructionSiteId = site.constructionSiteId;
      props.dispatch({
        type: 'construction/del',
        payload: { constructionId: constructionSiteId },
      });
      map.removeOverlay(marker);
    };
    var markerMenu = new BMap.ContextMenu();
    markerMenu.addItem(
      new BMap.MenuItem('删除设备', watchDelMarker.bind(marker)),
    );
    marker.addContextMenu(markerMenu);
  };

  const getMap = () => {
    map = new BMap.Map('allMap', { mapType: BMAP_HYBRID_MAP }); // 创建Map实例
    map.centerAndZoom('成都', 9); // 初始化地图,设置中心点坐标和地图级别
    map.addControl(new BMap.MapTypeControl()); //添加地图类型控件
    map.setCurrentCity('成都'); // 设置地图显示的城市 此项是必须设置的
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

    console.log(props);
    if (props.constructionList) {
      props.constructionList.map((item, index) => {
        var pt = new BMap.Point(item.latitude, item.longitude);
        var marker = new BMap.Marker(pt, {
          icon: blueIcon,
        });
        map.addOverlay(marker);
        var opts = {
          width: 210,
          height: 125,
          title: '<p>' + item.constructionSiteName + '</p>',
          enableMessage: true, //设置允许信息窗发送短息
          message: '',
        };
        var infoWindow = new BMap.InfoWindow(
          '<br>创建时间：' +
            item.createTime +
            '<br>经度：' +
            item.latitude +
            '<br>纬度' +
            item.longitude,
          opts,
        );
        marker.addEventListener('click', function () {
          // console.log('123');
          this.map.openInfoWindow(infoWindow, pt);
        });
        rightClickMarker(marker, pt, item);

        var overlays = [];
        var overlayComplete = function (e) {
          console.log(e.overlay);
          overlays.push(e.overlay);
        };
        var styleOptions = {
          strokeColor: 'red',
          fillColor: 'red',
          strokeWeight: 2,
          strokeOpacity: 0.6,
          strokeStyle: 'solid',
        };
        var drawingManager = new BMapLib.DrawingManager(map, {
          isOpen: false, //是否开启绘制模式
          enableDrawingTool: true, //是否显示工具栏
          drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
          },
          circleOptions: styleOptions, //圆的样式
        });
        drawingManager.addEventListener('overlayComplete', overlayComplete);
        function clearAll() {
          for (var i = 0; i < overlays.length; i++) {
            map.removeOverlay(overlays[i]);
          }
          overlays.length = 0;
        }
      });
      // function CircleOverlay(center, radius, color) {
      //   console.log(radius);
      //   this._center = center;
      //   this._radius = radius;
      //   this._color = color;
      // }
      // CircleOverlay.prototype = new BMap.Overlay();
      // CircleOverlay.prototype.initialize = function (map) {
      //   this._map = map;
      //   var div =document.createElement("div");
      //   div.style.position = "absolute";
      //   div.style.borderRadius = "50%";
      //   div.style.width = this._radius * 2 + 'px';
      //   div.style.height = this._radius * 2 + 'px';
      //   div.style.background= '1px' + 'solid' + this._color ;
      //   // 将div添加到覆盖物容器中
      //   map.getPanes().markerPane.appendChild(div);
      //   // 保存div实例
      //   this._div = div;
      //   // 需要将div元素作为方法的返回值，当调用该覆盖物的show、
      //   // hide方法，或者对覆盖物进行移除时，API都将操作此元素。
      //   return div;
      // }
      // CircleOverlay.prototype.draw = function () {
      //   var position = this._map.pointToOverlayPixel(this._center);
      //   this._div.style.left = position.x - this._radius + "px";
      //   this._div.style.top = position.y - this._radius + "px";
      // }
      // props.fenceList.map(item => {
      //   var myCircle = new CircleOverlay(map.getCenter(), 100, "red")
      //   console.log(myCircle);
      //   map.addOverlay(myCircle)
      // })
    }
  };
  // async function getListAndMap() {
  //   await props.dispatch({
  //     type: 'construction/fetch'
  //   })
  //   getMap()
  // }
  useLayoutEffect(() => {
    props.dispatch({
      type: 'construction/fetch',
    });
    props.dispatch({
      type: 'construction/fetchFence',
    });
    getMap();
  }, []);

  const onCreate = () => {
    hiddenModal();
    // add();
  };

  const hiddenModal = () => {
    setVisible(false);
  };
  const add = () => {
    setVisible(true);
  };

  return (
    <PageContainer>
      <div>
        <Button type="primary" style={{ marginBottom: '10px' }} onClick={add}>
          添加工地
        </Button>
      </div>
      <div ref={mapRef}>
        <div
          id="allMap"
          style={{
            width: '80vw',
            height: '69vh',
          }}
        ></div>
      </div>
      <CollectionCreateForm
        props={props}
        visible={visible}
        onCreate={onCreate}
        onCancel={hiddenModal}
      />
    </PageContainer>
  );
};
export default connect(({ construction }) => ({
  constructionList: construction.constructionList,
  fenceList: construction.fenceList,
}))(HomePage);
